package com.lovezy.platform.filestore.service;

import com.google.common.collect.ImmutableMap;
import com.lovezy.platform.common.prop.Constant;
import com.lovezy.platform.core.base.AppServer;
import com.lovezy.platform.core.codec.CodecUtil;
import com.lovezy.platform.filestore.model.File;
import com.lovezy.platform.filestore.oss.OssBucket;
import com.lovezy.platform.filestore.oss.OssBucketChooser;
import com.lovezy.platform.filestore.oss.QiniuOssProperties;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by jin on 2018/1/21.
 */

@Slf4j
public class QiniuFileHelper implements FileHelper {

    @Autowired
    QiniuOssProperties properties;

    @Autowired
    AppServer appServer;

    @Autowired
    OssBucketChooser ossBucketChooser;

    @Autowired
    FileService fileService;

    private String callbackUrl;

    @PostConstruct
    public void init() {
        callbackUrl = appServer.getDomain() + "open/upload/qiniuCallback";
    }

    @Override
    public String toDownloadUrl(String url) {
        File file = fileService.findFileByUrl(url);
        return toDownloadUrl(file);
    }

    @Override
    public @Nullable String toDownloadUrl(File file) {
        if (file == null) {
            return null;
        }
        String dir = file.getDir();
        OssBucket ossBucket = ossBucketChooser.bucketNameOf(dir);
        if (ossBucket.isOpen()) {
            return openDownloadUrl(file);
        }else{
            return privateDownloadUrl(file);
        }
    }

    private String openDownloadUrl(File file) {
//        String name = file.getName();
        String domain = properties.getOpenDomain();
        return downloadUrl(file, domain);

    }

    private String privateDownloadUrl(File file) {
        String publicUrl = downloadUrl(file,properties.getDomain());
        Auth auth = Auth.create(properties.getAccessId(), properties.getSecretKey());
        long expireInSeconds = Constant.DOWNLOAD_URL_EXPIRE;
        return auth.privateDownloadUrl(publicUrl, expireInSeconds);
    }

    private String downloadUrl(File file, String domain) {
        String url = file.getUrl();
        String encodedFileName = url;
        try {
            encodedFileName = URLEncoder.encode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            //ignore
            log.error("下载啊编码失败", e);
        }
        return String.format("%s/%s", domain, encodedFileName);
    }

    @Override
    public @NotNull byte[] getFileByteArray(File dbFile) {
        return new byte[0];
    }

    @Override
    public void storeFile(InputStream inputStream, File fileData) {

    }

    @Override
    public Map<String,String> createToken(String bucket, String fileName) {
        String accessId = properties.getAccessId();
        String secretKey = properties.getSecretKey();
        String fileKey = CodecUtil.uuid() + getFileExtension(fileName);

        Auth auth = Auth.create(accessId, secretKey);
        StringMap putPolicy = new StringMap();
        putPolicy.put("callbackUrl", callbackUrl);
        putPolicy.put("callbackBody", "{\"fileKey\":\"$(key)\",\"hash\":\"$(etag)\",\"dir\":\"$(bucket)\",\"size\":$(fsize),\"name\":$(fname),\"mimeType\":$(mimeType),\"userToken\":$(x:userToken)}");
        putPolicy.put("callbackBodyType", "application/json");
        long expireSeconds = Constant.UPLOAD_TOKEN_EXPIRE_SECOND;

        String upToken = auth.uploadToken(bucket, fileKey, expireSeconds, putPolicy);
        return ImmutableMap.of("token", upToken,"fileKey",fileKey);
    }
}
